package cqrtplm.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.dto.DspfStatusModuleitemDTO;
import cqrtplm.entity.DspfStatusModuleitemDO;
import cqrtplm.entity.DspfStatusModuleitemsubDO;
import cqrtplm.entity.DspfStatusModuleitemsubgroupDO;
import cqrtplm.mapper.DspfStatusModuleitemMapper;
import cqrtplm.mapper.DspfStatusModuleitemsubMapper;
import cqrtplm.mapper.DspfStatusModuleitemsubgroupMapper;
import cqrtplm.vo.TemplateInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 需求状态模版通过类似创建来复制的切面
 */
@Aspect
@Component
@Slf4j
public class ModuleitemSimilarCreateAOP {

    @Resource
    private DspfStatusModuleitemMapper dspfStatusModuleitemMapper;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private DspfStatusModuleitemsubMapper dspfStatusModuleitemsubMapper;
    @Resource
    private DspfStatusModuleitemsubgroupMapper dspfStatusModuleitemsubgroupMapper;
    /**
     * 在 TyplmBomController.similarCreate 方法执行后切入，获取返回值和请求参数进行处理
     */
    @AfterReturning(
            pointcut = "execution(* com.hustcad.plm.pdm.partbom.controller.TyplmBomController.similarCreate(..)) && args(fileList, request)",
            returning = "result"
    )
    public void afterSimilarCreate(List<MultipartFile> fileList, HttpServletRequest request, Object result) {
        try {
            // 解析请求参数中的JSON字符串
            String similarCreateDTOJson = request.getParameter("similarCreateDTO");
            if (similarCreateDTOJson == null || similarCreateDTOJson.isEmpty()) {
                return;
            }

            JSONObject jsonObject = JSON.parseObject(similarCreateDTOJson);
            if (jsonObject == null) {
                return;
            }

            // 获取 fatherOid
            String fatherOid = jsonObject.getString("fatherOid");
            if (fatherOid == null || fatherOid.isEmpty()) {
                return;
            }

            // 检查返回结果是否包含正确的数据类型
            if (result == null) {
                return;
            }

            // 直接类型检查和转换
            if (result.getClass().getSimpleName().equals("ResponseResult")) {
                try {
                    // 通过反射调用getData方法
                    java.lang.reflect.Method getDataMethod = result.getClass().getMethod("getData");
                    Object dataObj = getDataMethod.invoke(result);

                    if (dataObj != null) {
                        // 获取typeotype和masteredoid
                        String typeotype = (String) getObjectFieldValue(dataObj, "typeotype");
                        BigInteger masteredoid = (BigInteger) getObjectFieldValue(dataObj, "masteredoid");

                        final String EXPECTED_TYPE = "ty.inteplm.part.CTyPart|状态需求模板";
                        if (EXPECTED_TYPE.equals(typeotype) && masteredoid != null) {
                            // 开始复制模板操作
                            handleBusinessLogic(fatherOid, String.valueOf(masteredoid));
                        }
                    }
                } catch (Exception e) {
                   return;

                }
            }

        } catch (Exception e) {
            log.error("afterSimilarCreate error", e);
        }
    }

    private Object getObjectFieldValue(Object obj, String fieldName) {
        try {
            // 先尝试直接字段访问
            java.lang.reflect.Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return  field.get(obj);
        } catch (Exception e) {
            try {
                // 再尝试getter方法访问
                String methodName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
                java.lang.reflect.Method method = obj.getClass().getMethod(methodName);
                return method.invoke(obj);
            } catch (Exception ex) {
                log.warn("无法获取字段 {} 的值", fieldName);
                return null;
            }
        }
    }



    /**
     * 处理业务逻辑的方法
     * @param fatherOid 父对象ID
     * @param masteredoid 主控对象ID
     */
    private void handleBusinessLogic(String fatherOid, String masteredoid) {
        UserDO user = TyAccountContext.getUser();
        //获取原模版的id  通过当前oid查找masteredoid
        BigInteger fatherMasteredoid = dspfStatusModuleitemMapper.selectMasteredoidByOid(fatherOid);
        List<DspfStatusModuleitemDO> items = new ArrayList<>();
        List<DspfStatusModuleitemsubDO> subItems = new ArrayList<>();
        TemplateInfoVO defaultTemplates = new TemplateInfoVO(String.valueOf(fatherMasteredoid),"");
        copyTemplateFromExisting(defaultTemplates, masteredoid, String.valueOf(user.getOid()), user.getName(), new Date(), items, subItems);

    }


    /**
     * 从现有模板复制数据
     */
    private void copyTemplateFromExisting(TemplateInfoVO defaultTemplates, String newModuleId, String userId,
                                          String userName, Date createDate, List<DspfStatusModuleitemDO> items,
                                          List<DspfStatusModuleitemsubDO> subItems) {
        // 获取默认模板的数据
        DspfStatusModuleitemDTO defaultModuleItemDTO = new DspfStatusModuleitemDTO();
        defaultModuleItemDTO.setModuleId(defaultTemplates.getModuleId());
        List<DspfStatusModuleitemDO> defaultItems = dspfStatusModuleitemMapper.selectByMoudleId(defaultModuleItemDTO);

        // 创建ID映射关系，用于替换parentId
        Map<String, String> idMapping = new HashMap<>();
        idMapping.put("-1", "-1"); // 根节点保持不变

        // 先建立完整的ID映射关系
        for (DspfStatusModuleitemDO defaultItem : defaultItems) {
            String newId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
            idMapping.put(defaultItem.getItemId(), newId);
        }

        // 复制并更新item数据
        for (DspfStatusModuleitemDO defaultItem : defaultItems) {
            String newId = idMapping.get(defaultItem.getItemId());
            DspfStatusModuleitemDO newItem = new DspfStatusModuleitemDO();

            // 复制所有属性
            copyModuleItemProperties(defaultItem, newItem, newId, newModuleId, userId, userName, createDate);

            // 处理parentId映射
            String oldParentId = defaultItem.getParentId();
            String newParentId = idMapping.getOrDefault(oldParentId, oldParentId);
            newItem.setParentId(newParentId);

            items.add(newItem);
        }

        // 复制subItem数据
        // 用于存储sid映射关系 (oldSid -> newSid)
        Map<String, String> sidMapping = new HashMap<>();

        // 收集所有需要查询的itemId
        List<String> itemIds = defaultItems.stream()
                .map(DspfStatusModuleitemDO::getItemId)
                .collect(Collectors.toList());

        if (!itemIds.isEmpty()) {
            // 批量查询所有相关的subItem
            List<DspfStatusModuleitemsubDO> allSubItems = dspfStatusModuleitemsubMapper.selectByItemIds(itemIds);

            // 按itemId分组
            Map<String, List<DspfStatusModuleitemsubDO>> subItemsGroupedByItemId = allSubItems.stream()
                    .collect(Collectors.groupingBy(DspfStatusModuleitemsubDO::getItemId));

            // 处理每个defaultItem及其对应的subItems
            for (DspfStatusModuleitemDO defaultItem : defaultItems) {
                String oldItemId = defaultItem.getItemId();
                String newItemId = idMapping.get(oldItemId);

                // 获取该item对应的所有subItem
                List<DspfStatusModuleitemsubDO> oldSubItems = subItemsGroupedByItemId.getOrDefault(oldItemId, Collections.emptyList());

                // 复制每个subItem
                for (DspfStatusModuleitemsubDO oldSubItem : oldSubItems) {
                    DspfStatusModuleitemsubDO newSubItem = new DspfStatusModuleitemsubDO();
                    String newSid = String.valueOf(snowflakeIdComponent.getInstance().nextId());

                    // 复制所有属性
                    copyModuleItemSubProperties(oldSubItem, newSubItem, newSid, newModuleId, newItemId, userId, userName, createDate);
                    subItems.add(newSubItem);

                    // 记录sid映射关系
                    sidMapping.put(oldSubItem.getSid(), newSid);
                }
            }
        }
        // 复制群组信息
        copyModuleItemSubGroupInfo(defaultTemplates.getModuleId(), newModuleId, sidMapping, userId, userName, createDate);
        // 执行批量插入
        dspfStatusModuleitemMapper.insertByBatch(items);
        dspfStatusModuleitemsubMapper.insertByBatch(subItems);

    }


    /**
     * 复制RT_CFG_STATUSMODULEITEMSUBGROUP表中的群组信息
     */
    private void copyModuleItemSubGroupInfo(String oldModuleId, String newModuleId, Map<String, String> sidMapping,
                                            String userId, String userName, Date createDate) {
        // 如果没有sid映射关系，直接返回
        if (sidMapping.isEmpty()) {
            return;
        }

        // 批量查询所有需要复制的群组信息
        List<DspfStatusModuleitemsubgroupDO> oldGroupItems = dspfStatusModuleitemsubgroupMapper.selectByModuleId(oldModuleId);

        List<DspfStatusModuleitemsubgroupDO> newGroupItems = new ArrayList<>();
        for (DspfStatusModuleitemsubgroupDO oldGroupItem : oldGroupItems) {
            // 检查该groupItem对应的sid是否在映射中
            String newSid = sidMapping.get(oldGroupItem.getSid());
            if (newSid != null) {
                DspfStatusModuleitemsubgroupDO newGroupItem = new DspfStatusModuleitemsubgroupDO();
                // 复制属性
                copyModuleItemSubGroupProperties(oldGroupItem, newGroupItem, newSid, newModuleId, userId, userName, createDate);
                newGroupItems.add(newGroupItem);
            }
        }

        // 批量插入新的群组信息
        if (!newGroupItems.isEmpty()) {
            dspfStatusModuleitemsubgroupMapper.insertByBatch(newGroupItems);
        }
    }
    /**
     * 复制DspfStatusModuleitemDO属性
     */
    private void copyModuleItemProperties(DspfStatusModuleitemDO source, DspfStatusModuleitemDO target,
                                          String newItemId, String newModuleId, String userId, String userName, Date createDate) {
        target.setItemId(newItemId);
        target.setModuleId(newModuleId);
        target.setParentId(source.getParentId());
        target.setItemName(source.getItemName());
        target.setItemType(source.getItemType());
        target.setPositionNum(source.getPositionNum());
        target.setSortOrder(source.getSortOrder());
        target.setAuthorityRoleCode(source.getAuthorityRoleCode());
        target.setRemarks(source.getRemarks());
        target.setLvl(source.getLvl());
        target.setFSortCode(source.getFSortCode());
        target.setFDeleteMark(source.getFDeleteMark());
        target.setFEnabledMark(source.getFEnabledMark());
        target.setFDescription(source.getFDescription());
        target.setFCreateDate(createDate);
        target.setFCreateUserId(userId);
        target.setFCreateUserName(userName);
        target.setFModifyDate(null);
        target.setFModifyUserId(null);
        target.setFModifyUserName(null);
        target.setFDeleteDate(null);
        target.setItemCode(source.getItemCode());
        //        target.setShortDescription(source.getShortDescription());
    }


    /**
     * 复制DspfStatusModuleitemsubDO属性
     */
    private void copyModuleItemSubProperties(DspfStatusModuleitemsubDO source, DspfStatusModuleitemsubDO target,
                                             String newSid, String newModuleId, String newItemId, String userId,
                                             String userName, Date createDate) {
        target.setSid(newSid);
        target.setItemId(newItemId);
        target.setModuleId(newModuleId);
        target.setDetailId(source.getDetailId());
        target.setSubType(source.getSubType());
        target.setDataItemCode(source.getDataItemCode());
        target.setPartsCode(source.getPartsCode());
        target.setPartsName(source.getPartsName());
        target.setDescrCode(source.getDescrCode());
        target.setDescrName(source.getDescrName());
        target.setIsOptional(source.getIsOptional());
        target.setSubName(source.getSubName());
        target.setDescrTypename(source.getDescrTypename());
        target.setDescrTypeCode(source.getDescrTypeCode());
        target.setDescrValueCode(source.getDescrValueCode());
        target.setProductClass(source.getProductClass());
        target.setDefaultValue(source.getDefaultValue());
        target.setDefaultText(source.getDefaultText());
        target.setSortOrder(source.getSortOrder());
        target.setNotFromBom(source.getNotFromBom());
        target.setFSortCode(source.getFSortCode());
        target.setFDeleteMark(source.getFDeleteMark());
        target.setFEnabledMark(source.getFEnabledMark());
        target.setFDescription(source.getFDescription());
        target.setFCreateDate(createDate);
        target.setFCreateUserid(userId);
        target.setFCreateUserName(userName);
        target.setFModifyDate(null);
        target.setFModifyUserId(null);
        target.setFModifyUserName(null);
        target.setFixValue(source.getFixValue());
        target.setFixText(source.getFixText());
        target.setSourceRange(source.getSourceRange());
        target.setEditByXMZ(source.getEditByXMZ());
        target.setEditByZTS(source.getEditByZTS());
        target.setFDeleteDate(null);
        target.setSubProjectLeader(source.getSubProjectLeader());
        target.setEditByPack(source.getEditByPack());
        target.setEditByDecal(source.getEditByDecal());
        target.setEditByElectric(source.getEditByElectric());
        target.setEditByDL(source.getEditByDL());
        target.setEditByJZ(source.getEditByJZ());
        target.setLinkPartCodes(source.getLinkPartCodes());
        target.setMapperName(source.getMapperName());
//        target.setAttributeIds(source.getAttributeIds());
    }


    /**
     * 复制DspfStatusModuleitemsubgroupDO属性
     */
    private void copyModuleItemSubGroupProperties(DspfStatusModuleitemsubgroupDO source, DspfStatusModuleitemsubgroupDO target,
                                                  String newSid, String newModuleId, String userId, String userName, Date createDate) {
        // 生成新的主键ID
        target.setOid(snowflakeIdComponent.getInstance().nextId());
        target.setSid(newSid);
        target.setGroupId(source.getGroupId());
        target.setGroupName(source.getGroupName());
        target.setIsEdit(source.getIsEdit());
        target.setIsDisplayed(source.getIsDisplayed());
        target.setIsDelete(source.getIsDelete());
        target.setCreateTime(createDate);
        target.setCreateUserId(new BigInteger(userId));
        target.setCreateUsername(userName);
        target.setUpdateTime(null);
        target.setUpdateUserId(null);
        target.setUpdateUsername(null);
        target.setDeleteTime(null);
        target.setDeleteUserId(null);
        target.setDeleteUsername(null);
        target.setModuleId(newModuleId); // 设置新的moduleId
    }


}
